<!-- templates/history.html -->
{% extends "base.html" %}

{% block title %}代码历史 - {{ super() }}{% endblock %}

{% block extra_css %}
<style>
    .card {
        background: rgb(206, 206, 206)!important;
        border-radius: 24px !important;
        overflow: hidden; /* 确保子元素圆角不溢出 */
    }
    .score-badge {
        border-radius: 24px !important;
        font-size: 0.9rem;
        min-width: 70px;
        text-align: center;
        transition: transform 0.2s;
    }
    .score-badge:hover {
        border-radius: 24px !important;
        transform: scale(1.05);
    }
    .history-preview {
        background: rgb(206, 206, 206)!important;
        border-radius: 24px !important;
        font-family: Monaco, Consolas, 'Courier New', monospace;
        color: #495057;
    }
    .modal-pre {
        background: rgb(206, 206, 206)!important;
        padding: 1rem;
        border-radius: 24px !important;
        max-height: 60vh;
        overflow-y: auto;
    }
    .filter-toolbar {
        background: rgb(206, 206, 206)!important;
        padding: 1.5rem;
        border-radius: 24px !important;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    .form-label {
        background: rgb(206, 206, 206)!important;
        font-weight: 500;
        color: #495057;
        font-size: 0.9rem;
    }
    #startDate, #endDate {
        background: rgb(206, 206, 206)!important;
        transition: border-color 0.3s ease;
        
    }
    #startDate:focus, #endDate:focus {
        border-color: #0d6efd;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }
</style>
{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-lg-10">
        <div class="card shadow">
            <div class="card-header bg-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h4 class="mb-0"><i class="fas fa-history me-2"></i>代码提交历史</h4>
                    <button class="btn btn-sm btn-outline-secondary" onclick="resetFilters()">
                        <i class="fas fa-sync me-1"></i>重置筛选
                    </button>
                </div>
            </div>
            
            <!-- 筛选工具栏 -->
            <div class="card-body border-bottom">
                <div class="row g-3 align-items-center filter-toolbar">
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-calendar-start me-2"></i>开始日期</label>
                        <input type="date" id="startDate" class="form-control">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-calendar-end me-2"></i>结束日期</label>
                        <input type="date" id="endDate" class="form-control">
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button class="btn btn-primary w-100" onclick="loadHistory()">
                            <i class="fas fa-filter me-2"></i>筛选记录
                        </button>
                    </div>
                </div>
            </div>

            <div class="card-body">
                <div id="loading" class="spinner-container">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>

                <div id="history-list" class="list-group d-none">
                    <!-- 动态加载历史记录 -->
                </div>

                <div id="empty-message" class="text-center text-muted py-4 d-none">
                    <i class="bi bi-clock-history fs-1"></i>
                    <p class="mt-2">暂无提交记录</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadHistory();

    // 历史记录点击处理
    document.getElementById('history-list').addEventListener('click', function(e) {
        if (e.target.classList.contains('view-btn')) {
            const historyId = e.target.dataset.historyId;
            fetchHistoryDetail(historyId);
        }
    });
});

function getScoreClass(score) {
    if (score >= 8) return 'bg-success';
    if (score >= 5) return 'bg-warning';
    return 'bg-danger';
}

function loadHistory() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    // 日期有效性检查
    if (startDate && endDate && new Date(startDate) > new Date(endDate)) {
        alert('结束日期不能早于开始日期');
        return;
    }

    // 显示加载状态
    document.getElementById('loading').classList.remove('d-none');
    document.getElementById('history-list').classList.add('d-none');
    document.getElementById('empty-message').classList.add('d-none');

    // 构建查询参数
    const params = new URLSearchParams();
    if (startDate) params.append('start_date', startDate);
    if (endDate) params.append('end_date', endDate);

    fetch(`/api/history?${params.toString()}`)
        .then(response => {
            if (!response.ok) throw new Error('请求失败');
            return response.json();
        })
        .then(data => {
            document.getElementById('loading').classList.add('d-none');
            
            const listContainer = document.getElementById('history-list');
            const emptyMsg = document.getElementById('empty-message');
            
            if (data.length === 0) {
                emptyMsg.classList.remove('d-none');
                return;
            }

            listContainer.innerHTML = data.map(item => `
                <div class="list-group-item">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="me-3 flex-grow-1">
                            <div class="d-flex align-items-center mb-2">
                                <span class="badge ${getScoreClass(item.score)} score-badge me-2">
                                    ${item.score?.toFixed(1) || 'N/A'} 分
                                </span>
                                <small class="text-muted">${item.timestamp}</small>
                            </div>
                            <div class="history-preview">${item.preview}</div>
                        </div>
                        <button class="btn btn-sm btn-outline-primary view-btn" 
                                data-history-id="${item.id}">
                            <i class="fas fa-eye me-1"></i>详情
                        </button>
                    </div>
                </div>
            `).join('');

            listContainer.classList.remove('d-none');
        })
        .catch(error => {
            console.error('加载失败:', error);
            alert('筛选失败: ' + error.message);
        });
}

function resetFilters() {
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    loadHistory();
}

function fetchHistoryDetail(historyId) {
    fetch(`/api/history/${historyId}`)
        .then(response => response.json())
        .then(data => {
            const codeContent = data.code.replace(/</g, '&lt;').replace(/>/g, '&gt;');
            const modalHtml = `
                <div class="modal fade" id="codeModal">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">
                                    <span class="badge ${getScoreClass(data.score)} me-2">
                                        ${data.score?.toFixed(1) || 'N/A'} 分
                                    </span>
                                    代码详情
                                </h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <pre class="modal-pre">${codeContent}</pre>
                                <div class="mt-3 text-muted small">
                                    <i class="fas fa-clock me-1"></i>
                                    提交时间：${data.timestamp}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            const modalContainer = document.createElement('div');
            modalContainer.innerHTML = modalHtml;
            document.body.appendChild(modalContainer);
            
            const modal = new bootstrap.Modal(document.getElementById('codeModal'));
            modal.show();
            
            // 模态框关闭后移除元素
            document.getElementById('codeModal').addEventListener('hidden.bs.modal', () => {
                modalContainer.remove();
            });
        })
        .catch(error => {
            console.error('加载失败:', error);
            alert('无法加载代码详情');
        });
}
</script>
{% endblock %}